import { EventStreamService } from './eventStream';
import type { ChatConfig, ChatMessage } from '../types/chat';
import { logger } from '../utils/logger'

/**
 * 聊天API服务
 */
export class ChatApiService {
  private config: ChatConfig;
  private eventStreamService: EventStreamService;
  
  /**
   * 构造函数
   * @param config 聊天配置
   * @param debug 是否启用调试模式
   */
  constructor(config: ChatConfig, debug: boolean = false) {
    this.config = config;
    this.eventStreamService = new EventStreamService();
  }
  
  /**
   * 获取事件流服务实例
   */
  getEventStreamService(): EventStreamService {
    return this.eventStreamService;
  }
  
  /**
   * 发送聊天消息并获取流式响应
   * @param messages 聊天历史
   * @param enableTts 是否启用语音合成
   */
  async sendChatMessage(messages: ChatMessage[], enableTts: boolean = false): Promise<void> {
    try {
      // 获取最新的用户消息
      const latestUserMessage = messages.filter(m => m.role === 'user').pop();
      if (!latestUserMessage) {
        throw new Error('没有找到用户消息');
      }
      
      // 构造请求对象
      const requestBody = {
        inputs: {},
        query: latestUserMessage.content,
        response_mode: "streaming",
        conversation_id: "", 
        user: this.config.userId,
        // enable_tts: enableTts,
        files: []
      };
      
      // 使用相对路径
      const apiUrl = '/api/v1/chat-messages';
      // 发送请求
      const response = await fetch(apiUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'text/event-stream',
          'Authorization': `Bearer ${this.config.apiKey}`
        },
        body: JSON.stringify(requestBody)
      });
      
      // 检查响应状态
      if (!response.ok) {
        let errorMessage = `HTTP错误: ${response.status}`;
        try {
          const errorData = await response.json();
          errorMessage = errorData.message || errorMessage;
        } catch (e) { }
        throw new Error(errorMessage);
      }
      
      if (!response.body) {
        throw new Error('响应体为空');
      }
      await this.eventStreamService.processEventStream(response);   
    } catch (error) {
      logger.error('ChatApi', '发送聊天消息失败', error)
      throw error;
    }
  }
  
  /**
   * 中止当前请求
   * @param taskId 任务ID
   */
  async abortRequest(taskId: string): Promise<void> {
    if (!taskId) return;
    
    try {
      await fetch(`/api/v1/chat-messages/${taskId}/stop`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.config.apiKey}`
        },
        body: JSON.stringify({
          user: this.config.userId
        })
      });
    } catch (error) {
      logger.error('ChatApi', '取消请求失败', error)
      throw error;
    }
  }

  /**
   * 下载文件
   * @param datasetId 数据集ID
   * @param documentId 文档ID
   * @returns 文件信息
   */
  async downloadFile(datasetId: string, documentId: string): Promise<{
    id: string;
    name: string;
    size: number;
    extension: string;
    url: string;
    download_url: string;
    mime_type: string;
    created_by: string;
    created_at: number;
  }> {
    try {
      const response = await fetch(`/api/v1/datasets/${datasetId}/documents/${documentId}/upload-file`, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${this.config.dataset_Key}`,
          'Content-Type': 'application/json'
        }
      });

      if (!response.ok) {
        let errorMessage = `HTTP错误: ${response.status}`;
        try {
          const errorData = await response.json();
          errorMessage = errorData.message || errorMessage;
        } catch (e) { }
        throw new Error(errorMessage);
      }

      return await response.json();
    } catch (error) {
      logger.error('ChatApi', '下载文件失败', error)
      throw error;
    }
  }
} 